package cn.lingyangwl.agile.infra.file.constant;

import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.Arrays;

/**
 * 通过识别base64前缀判断文件类型
 *
 * @author shenguangyang
 */
@Getter
@AllArgsConstructor
public enum Base64TypeEnum {
    UNKNOWN("data:application/octet-stream;base64", ""),
    TEXT_2("data:text/plain;base64", "txt"),
    DOC("data:application/msword;base64", "doc"),
    DOCX("data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64", "docx"),
    XLS("data:application/vnd.ms-excel;base64", "xls"),
    XLSX("data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64", "xlsx"),
    PDF("data:application/pdf;base64", "pdf"),
    PPT("data:application/vnd.ms-powerpoint;base64", "ppt"),
    PPTX("data:application/vnd.openxmlformats-officedocument.presentationml.presentation;base64", "pptx"),
    HTML("data:text/html;base64", "html"),
    CSS("data:text/css;base64", "css"),
    JAVASCRIPT("data:text/javascript;base64", "js"),
    GIF("data:image/gif;base64", "gif"),
    PNG("data:image/png;base64", "png"),
    JPEG("data:image/jpeg;base64", "jpeg"),
    JPG("data:image/jpg;base64", "jpg"),
    ICON("data:image/x-icon;base64", "ico"),
    svg("data:image/svg+xml;base64", "svg"),

    ;
    private final String pre;
    private final String type;

    public static Base64TypeEnum ofByBase64(String base64) {
        String[] split = base64.split("base64,");
        if (split.length != 2) {
            return UNKNOWN;
        }
        String base64Pre = split[0];
        return Arrays.stream(Base64TypeEnum.values()).filter(e -> e.pre.startsWith(base64Pre))
                .findFirst().orElse(Base64TypeEnum.UNKNOWN);
    }

    public String getExt() {
        return this == Base64TypeEnum.UNKNOWN ? "" : "." + this.getType();
    }

    public String getContentType() {
        return Base64TypeEnum.UNKNOWN.getPre().replaceFirst("data:", "")
                .replaceAll(";base64", "");
    }
}
